package com.mtauto.action.record;

import java.io.IOException;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

import org.codeanywhere.easyRestful.base.BaseAction;
import org.codeanywhere.easyRestful.base.RequestContext;
import org.codeanywhere.easyRestful.base.annotation.Json;
import org.codeanywhere.easyRestful.base.annotation.Request;
import org.codeanywhere.easyRestful.base.annotation.SpringBean;

import com.mtauto.model.Result;
import com.mtauto.service.MonkeyRunnerService;
import com.mtauto.service.MonkeyRunnerService.MonkeyRunnerProcess;

//TODO monkeyrunner相关操作都需要封装成异步超时机制
public class Record extends BaseAction {

    @Request
    private RequestContext                   rc;
    @SpringBean
    private MonkeyRunnerService              monkeyRunnerService;
    private Map<String, MonkeyRunnerProcess> mRunnerMap                  = new ConcurrentHashMap<String, MonkeyRunnerProcess>();
    private Map<String, TimerTask>           taskMap                     = new ConcurrentHashMap<String, TimerTask>();
    private static String                    snapshotPath;
    private static int                       TIME_TASK_INTERVAL_MILLIONS = 5000;
    static {
        ResourceBundle res = ResourceBundle.getBundle("mtauto");
        snapshotPath = res.getString("mtauto.snapshot.path");
    }

    public void execute() {
        String deviceId = rc.getHttpServletRequest().getParameter("deviceId");
        rc.put("deviceId", deviceId);
        try {
            createMonkeyRunnerInstance(deviceId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void createMonkeyRunnerInstance(String serialno) throws IOException,
            InterruptedException {
        if (mRunnerMap.get(serialno) == null) {
            synchronized (mRunnerMap) {
                if (mRunnerMap.get(serialno) == null) {
                    MonkeyRunnerProcess process = monkeyRunnerService.createMonkeyRunnerInstance(
                            serialno, (float) 60);
                    mRunnerMap.put(serialno, process);
                }
            }
        }
    }

    @Json
    public Result<?> startGetSnapshot(String serialno) {
        try {
            createMonkeyRunnerInstance(serialno);
        } catch (Exception e) {
            return Result.createFailResult(e.getMessage());
        }
        final MonkeyRunnerProcess mrp = mRunnerMap.get(serialno);
        final String img = mrp.getDeviceId() + ".png";
        if (taskMap.get(mrp.getDeviceId()) == null) {
            synchronized (taskMap) {
                if (taskMap.get(mrp.getDeviceId()) == null) {
                    TimerTask task = new TimerTask() {

                        @Override
                        public void run() {
                            try {
                                monkeyRunnerService.flashSnapshot(mrp, snapshotPath + img);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    };
                    taskMap.put(serialno, task);
                    mrp.getTimer().schedule(task, 0, TIME_TASK_INTERVAL_MILLIONS);
                }
            }
        }
        return Result.createResult(img);
    }

    @Json
    public Result<?> stopGetSnapshot(String serialno) {
        synchronized (taskMap) {
            TimerTask task = taskMap.get(serialno);
            task.cancel();
            taskMap.remove(serialno);
        }
        return Result.createResult("stop");
    }
}
